import pygame
import netc

pygame.init()

screen = pygame.display.set_mode((640,480))
conn = netc.UDPConn(2203, 2202)
addr = "127.0.0.1"
clock = pygame.time.Clock()

run = True

players = {}

#name = raw_input("Name> ")
name = "Kriuq2"

conn.send_data("connect "+name, addr)
ticks = 0

while run:
    clock.tick(30)
    ticks += 1
    if ticks > 30:
        ticks = 0
        conn.send_data("ping", addr)

    for data, addr in conn.recv_all_data():
        data = data.split()
        if data[0] == "newplayer":
            players[data[1]] = (int(data[2]),int(data[3]))
        elif data[0] == "player":
            players[data[1]] = (int(data[2]),int(data[3]))
        elif data[0] == "move":
            players[data[1]] = (int(data[2]),int(data[3]))
        elif data[0] == "killplayer":
            players.pop(data[1])
        elif data[0] == "connected":
            if data[1] == "True":
                print "Connection successful"

    #conn.send_data("ping", addr)

    screen.fill((255,255,255))

    for x,y in players.values():
        pygame.draw.circle(screen,(0,0,0),(x,y),20)

    pygame.display.update()

    for event in pygame.event.get():
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_UP:
                conn.send_data("data move up", addr)
            elif event.key == pygame.K_DOWN:
                conn.send_data("data move down", addr)
            elif event.key == pygame.K_LEFT:
                conn.send_data("data move left", addr)
            elif event.key == pygame.K_RIGHT:
                conn.send_data("data move right", addr)
            elif event.key == pygame.K_ESCAPE:
                conn.send_data("kill", addr)
                run = False

        if event.type == pygame.KEYUP:
            if event.key == pygame.K_UP:
                conn.send_data("data move down", addr)
            elif event.key == pygame.K_DOWN:
                conn.send_data("data move up", addr)
            elif event.key == pygame.K_LEFT:
                conn.send_data("data move right", addr)
            elif event.key == pygame.K_RIGHT:
                conn.send_data("data move left", addr)

        elif event.type == pygame.QUIT:
            run = False
            conn.send_data("disconnect", addr)
